<?php

namespace Biz\tools;

use Doraemon\pockets\config\IniConfig;
use OSS\Core\OssException;
use OSS\OssClient;
use Doraemon\tools\Log;

class FileUpload
{
    const _CONFIG_FILE_ = "img";

    const _CONFIG_SELECT = "aliyun_config";

    const _CONFIG_BUCKET = "aliyun_bucket";

    private static $_config = null;

    private static function initConfig()
    {
        if (is_null(self::$_config)) {
            self::$_config['config'] = IniConfig::getConfigSelect(self::_CONFIG_FILE_, self::_CONFIG_SELECT);
            self::$_config['bucket'] = IniConfig::getConfigSelect(self::_CONFIG_FILE_, self::_CONFIG_BUCKET);
        }
        return true;
    }

    /**
     * @param $file
     * @return bool|string false|$filename
     */
    public static function uploadFile($fileName, $file)
    {
        self::initConfig();
        $accessKeyId = self::$_config['config']['oss_access_id'];
        $accessKeySecret = self::$_config['config']['oss_access_key'];
        $endpoint = self::$_config['config']['oss_endpoint'];
        $bucket = self::$_config['bucket']['biz_file_bucket'];
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $pathInfo = pathinfo($fileName);
            $ext = $pathInfo['extension'];
            $ext = strtoupper($ext);
            $fileName = $pathInfo['basename'];
            $fileName = md5($fileName . time());
            $ossPath = date('Ymd');
            $fileName = $fileName . base_convert($ossPath, 10, 36) . '.' . $ext;
            $object = $ossPath . '/' . $fileName;
            $data = $ossClient->uploadFile($bucket, $object, $file);
            if ($data && $data['info'] && $data['info']['url']) {
                return $fileName;
            } else {
                Log::warning('上传文件失败#data:' . json_encode($data, JSON_UNESCAPED_UNICODE));
                return false;
            }
        } catch (OssException $e) {
            Log::warning('上传文件失败#code:' . $e->getErrorCode() . '#message:' . $e->getErrorMessage());
            return false;
        }
    }

    public static function getFile($fileName)
    {
        self::initConfig();
        $accessKeyId = self::$_config['config']['oss_access_id'];
        $accessKeySecret = self::$_config['config']['oss_access_key'];
        $endpoint = self::$_config['config']['oss_endpoint'];
        $bucket = self::$_config['bucket']['biz_file_bucket'];
        try {
            $fileId = strstr($fileName, '.', true);
            $ext = strstr($fileName, '.');
            $filePath = base_convert(substr($fileId, 32), 36, 10);
            $file = $filePath . '/' . $fileId . $ext;
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $content = $ossClient->getObject($bucket, $file);
            return $content;
        } catch (OssException $e) {
            Log::warning('获取文件失败#code:' . $e->getErrorCode() . '#message:' . $e->getErrorMessage());
            return false;
        }
    }

    public static function getFileOutPut($fileName)
    {
        self::initConfig();
        $accessKeyId = self::$_config['config']['oss_access_id'];
        $accessKeySecret = self::$_config['config']['oss_access_key'];
        $endpoint = self::$_config['config']['oss_endpoint'];
        $bucket = self::$_config['bucket']['biz_file_bucket'];
        try {
            $fileId = pathinfo($fileName, PATHINFO_FILENAME);
            $ext = pathinfo($fileName, PATHINFO_EXTENSION);
            $filePath = base_convert(substr($fileId, 32), 36, 10);
            $file = $filePath . '/' . $fileId . '.' .$ext;
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $content = $ossClient->getObject($bucket, $file);
            $ext = strtolower($ext);
            switch ($ext) {
                case 'png':
                case 'jpeg':
                case 'jpg':
                    header('Content-type: image/jpeg');
                    break;
                case 'pdf':
                    header('Content-type: application/pdf');
                    break;
                default:
                    throw new \Exception('非法文件');
                    break;
            }
            ob_end_clean();
            exit($content);
        } catch (OssException $e) {
            Log::warning('获取文件失败#code:' . $e->getErrorCode() . '#message:' . $e->getErrorMessage());
            return false;
        }
    }
}
